package jobs;


import java.io.File;
import java.net.URL;
import java.net.URLConnection;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.Properties;
import javax.mail.Message;
import javax.mail.Multipart;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.servlet.ServletContext;

import org.apache.log4j.Logger;
import org.jdom2.Document;
import org.jdom2.input.SAXBuilder;
import org.jdom2.output.Format;
import org.jdom2.output.XMLOutputter;
import org.quartz.Job;
import org.quartz.JobDataMap;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.quartz.SchedulerException;

import util.Utility;


public class BackupJob implements Job{

	private  Logger log = Logger.getLogger(getClass());



    public void execute(JobExecutionContext context)
        throws JobExecutionException {
    	//System.out.println("SONO DENTRO");
        JobDataMap data = context.getMergedJobDataMap();
        //recupera Url del DB
		Properties props = new Properties();
		props.put(Utility.PROP_SMTP_AUTH, data.getString(Utility.PROP_SMTP_AUTH));
		props.put(Utility.PROP_SMTP_STARTTLS, data.getString(Utility.PROP_SMTP_STARTTLS));
		props.put(Utility.PROP_SMTP_HOST,data.getString(Utility.PROP_SMTP_HOST));
		props.put(Utility.PROP_SMTP_PORT, data.getString(Utility.PROP_SMTP_PORT));
        final String user = data.getString(Utility.PROP_SMTP_USERNAME);
        final String pass = data.getString(Utility.PROP_SMTP_PASSWORD);
        String recipe = data.getString(Utility.PROP_SMTP_RECIPE);
        String from = data.getString(Utility.PROP_SMTP_FROM);
    	String dbLoc  = "";
    	ServletContext serv=null;    	
		try {
			serv = (ServletContext)context.getScheduler().getContext().get("ContextServ");
		} catch (SchedulerException e1) {
			// TODO Auto-generated catch block
			log.error(e1.getMessage());
		}
        dbLoc = serv.getRealPath("db");
        //System.out.println(dbLoc);
		
		try {
			SAXBuilder build = new SAXBuilder();
			XMLOutputter xmlOutput = new XMLOutputter();		 
			Document docum;
			File xmlFile;
			
			xmlFile = new File(dbLoc+File.separator+"Newsletter.xml");
			docum = (Document) build.build(xmlFile);			
			xmlOutput.setFormat(Format.getPrettyFormat());
			String docNews = xmlOutput.outputString(docum);

			xmlFile = new File(dbLoc+File.separator+"Eventi.xml");
			docum = (Document) build.build(xmlFile);			
			xmlOutput.setFormat(Format.getPrettyFormat());
			String docEventi = xmlOutput.outputString(docum);

			xmlFile = new File(dbLoc+File.separator+"Luoghi.xml");
			docum = (Document) build.build(xmlFile);			
			xmlOutput.setFormat(Format.getPrettyFormat());
			String docLuoghi = xmlOutput.outputString(docum);

			xmlFile = new File(dbLoc+File.separator+"Config.xml");
			docum = (Document) build.build(xmlFile);			
			xmlOutput.setFormat(Format.getPrettyFormat());
			String docConfig = xmlOutput.outputString(docum);

			xmlFile = new File(dbLoc+File.separator+"Utenti.xml");
			docum = (Document) build.build(xmlFile);			
			xmlOutput.setFormat(Format.getPrettyFormat());
			String docUtenti = xmlOutput.outputString(docum);

			//salviamo Inviamo una mail

	        Session session = Session.getInstance(props,
					  new javax.mail.Authenticator() {
						protected PasswordAuthentication getPasswordAuthentication() {
							return new PasswordAuthentication(user, pass);
						}
			});
	        
			Message message = new MimeMessage(session);
			message.setFrom(new InternetAddress(from));
			message.setRecipients(Message.RecipientType.TO,
				InternetAddress.parse(recipe));
			message.setSubject("inBOtta.it Backup Auto");
			message.setSentDate(new Date());
			//message.setText("QUANTO SEI FIGAAAA");
			   // create the message part 
		    MimeBodyPart messageBodyPart = 
		      new MimeBodyPart();

		    //fill message
		    messageBodyPart.setText("inBOtta.it AutoGenerated Backup");

		    Multipart multipart = new MimeMultipart();
		    multipart.addBodyPart(messageBodyPart);

		    // Part two is attachment
		    messageBodyPart = new MimeBodyPart();
		    messageBodyPart.setFileName("Newsletter.xml");
		    messageBodyPart.setContent(docNews,"text/xml");
		    multipart.addBodyPart(messageBodyPart);
		    
		    messageBodyPart = new MimeBodyPart();
		    messageBodyPart.setFileName("Utenti.xml");
		    messageBodyPart.setContent(docUtenti,"text/xml");
		    multipart.addBodyPart(messageBodyPart);
		    
		    messageBodyPart = new MimeBodyPart();
		    messageBodyPart.setFileName("Eventi.xml");
		    messageBodyPart.setContent(docEventi,"text/xml");
		    multipart.addBodyPart(messageBodyPart);
		    
		    messageBodyPart = new MimeBodyPart();
		    messageBodyPart.setFileName("Luoghi.xml");
		    messageBodyPart.setContent(docLuoghi,"text/xml");
		    multipart.addBodyPart(messageBodyPart);
		    
		    messageBodyPart = new MimeBodyPart();
		    messageBodyPart.setFileName("Config.xml");
		    messageBodyPart.setContent(docConfig,"text/xml");
		    multipart.addBodyPart(messageBodyPart);		    
			message.setContent(multipart);
			Transport.send(message);
			
		
		/*
		File dir1 = new File (".");
		File dir2 = new File ("..");
		   
		System.out.println ("Current dir : " + dir1.getCanonicalPath());
		System.out.println ("Parent  dir : " + dir2.getCanonicalPath());
		  */     
		
 
			//System.out.println("Done");
 
		} catch (Exception e) {
			//e.printStackTrace(); 
			getLog().error("backup fail"+e.getMessage() );
			 throw new JobExecutionException("Unable to send mail: ",
	                    e, false);
		}
		
		//MailInfo mailInfo = populateMailInfo(data, createMailInfo());
        
        //getLog().info("Sending message " + mailInfo);


    }

    protected Logger getLog() {
        return log;
    }
   /*
    //Find all the xml files in a specified directory and store them in a vector
    private  List<File> getXmlFiles(File filePath) {

	 List<File> files2add = new ArrayList<File>();

	String [] dirContents = filePath.list();
	if (dirContents != null) {
	    for (int i = 0; i < dirContents.length; i++) {
		File entry = new File(filePath + File.separator + dirContents[i]);
		if (entry.isFile() && entry.toString().toLowerCase().endsWith(".xml") && !entry.getName().startsWith("CopyOf_")) {
		    files2add.add(entry);

		}
	    }
	}
	return files2add;
   }
   */
 
}
